<?php


namespace app\index\controller\xilujob;


use app\common\controller\xilujob\Xilujob;
use app\common\model\xilujob\Area;
use app\common\model\xilujob\Benefit;
use app\common\model\xilujob\CompanyAddress;
use app\common\model\xilujob\CompanyStatistics;
use app\common\model\xilujob\Config;
use app\common\model\xilujob\EducationLevel;
use app\common\model\xilujob\EnterpriseInfo;
use app\common\model\xilujob\InformType;
use app\common\model\xilujob\Job;
use app\common\model\xilujob\JobApply;
use app\common\model\xilujob\JobBenefit;
use app\common\model\xilujob\JobLocation;
use app\admin\model\xilujob\SinglePage;
use app\common\model\xilujob\JobRefreshLog;
use app\common\model\xilujob\Salary;
use app\common\model\xilujob\WorkExperience;
use app\common\model\xilujob\XilujobUser;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;
use function fast\array_except;
use function fast\array_get;

class JobManage extends Xilujob {

    protected $noNeedLogin = [];

    protected $noNeedRight = ['*'];

    protected $restrictedActions = [];

    public function _initialize() {
        parent::_initialize();
        $this->model = new Job();
    }

    public function index() {
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            $jobCount = Job::where('publisher_id', $this->company->id)->count();
            $jobLimit = EnterpriseInfo::where('id', $this->company->id)->value('job_num_limit');
            $this->assign('job_count', $jobCount);
            $this->assign('job_limit', $jobLimit);
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $jobs = $this->model->with([
                'benefits',
                'city' => function ($query) {
                    $query->field('id,name');
                },
                'district' => function ($query) {
                    $query->field('id,name');
                },
                'work_experience',
                'education_level',
                'job_info' => function ($query) {
                    $query->field('id,job_id,failed_reason');
                },
            ])
                ->where('publisher_id', $this->company->id);
            switch ($this->request->param('type')) {
                case 1:
                    $jobs->where('in_hurry', 1);
                    break;
                case 4:
                    $jobs->where('red_packet', '>', 0);
                    break;
                default:
            }
            $jobs = $jobs->where($where)->paginate();
            $result = array("total" => $jobs->total(), "rows" => $jobs->items());

            return json($result);
        }
        $this->assignconfig('education_level',EducationLevel::order('weigh','asc')->column('id,name'));
        $this->assignconfig('expect_salary',Salary::where('option_type',3)->order('min','asc')->column('id,name'));
        $this->assignconfig('work_experience',WorkExperience::order('weigh','asc')->column('id,name'));
        $this->view->assign('title','职位列表');
        return $this->view->fetch();
    }


    public function add() {
        $jobCount = EnterpriseInfo::getAvailableNum($this->company->id,'job_publish');
        if($jobCount <= 0) {
            $this->error("您的职位套餐次数已用完，请购买套餐");
        }
        $user = $this->auth->getUser();
        $xilujobuser = XilujobUser::get(['user_id'=>$user->id]);
        if($this->request->isPost()) {
            $params = $this->request->post('job/a', '', 'trim');
            $params = array_merge($params, [
                'user_id'=>$user->id,'publisher_id' => $this->company->id, 'publisher_type' => $xilujobuser->enterprise_group_id, 'status' => Job::STATUS_AUDITING
            ]);
            $params = array_except($params, ['in_hurry']);//不允许前端修改

            $params['user_id'] = $this->auth->id;

            //工作地址
            $company_address_id = array_get($params,'company_address_id');
            if($company_address_id){
                $companyAddress = CompanyAddress::field("id as company_address_id,province_id,city_id,district_id,address_name,address,house_number,lat,lng")->where('id',$company_address_id)->find();
                $params['locations'][] = $companyAddress->toArray();
            }

            Db::startTrans();
            try {
                $job = Job::addJob($params);
            }catch (Exception $exception){
                Db::rollback();
                $this->error($exception->getMessage());
            }
            Db::commit();
            $url = url('xilujob.job_manage/index',['status'=>$job->status==1?'1':'audit']);

            $msg = $xilujobuser->enterprise_model->audit_status==2?'企业信息审核后方会在前台显示':'';

            $this->success($msg, $url, ['job' => $job]);
        }
        // 获得添加时的初始数据
        $job = ['type'=>1,'contact_person'=>$user->nickname,'contact_phone'=>$user->mobile,
            'contact_email'=>$user->email,'locations'=>[[]], 'benefit_ids'=>[]];
        //$this->assign('districts', Area::getDistrictsWith($this->city?$this->city->id:0));
        $this->assign('districts', []);
        $this->assign('benefits', Benefit::getBenefits());
        $this->assignconfig('areas', Area::getAreaTree());
        $this->assign('work_experience_options', WorkExperience::getAll());
        $this->assign('education_levels', EducationLevel::getAll());
        $this->assignconfig("isdialog", IS_DIALOG);
        $this->assign('agreement', SinglePage::where('short_tag','job_agreement')->find());

        //公司地址
        $companyAddress = CompanyAddress::where('company_id',$this->company->id)->select();
        $this->assign('companyAddress',$companyAddress);

        return $this->view->fetch('add', ['job'=>$job]);
    }

    public function edit($ids=NULL) {
        $job = Job::get($ids);
        if (!$job || $job->publisher_id != $this->company->id) {
            $this->error(__('no record'));
        }
        if($this->request->isPost()) {
            $params = $this->request->post('job/a', '', 'trim');
            if($job->status==Job::STATUS_ENABLED) {
                $this->error('招聘中的职位无法编辑');
            }
//            if($job->status==Job::STATUS_AUDITING) {
//                $this->error('审核中的职位无法编辑');
//            }
            $params = array_except($params,['in_hurry']);//不允许前端修改

            //工作地址
            $company_address_id = array_get($params,'company_address_id');
            if($company_address_id){
                $companyAddress = CompanyAddress::field("id as company_address_id,province_id,city_id,district_id,address_name,address,house_number,lat,lng")->where('id',$company_address_id)->find();
                $params['locations'][] = $companyAddress->toArray();
            }
            try{
                $job = Job::editJob($job, $params);
            }catch (Exception $e){
                $this->error($e->getMessage());
            }
            $job->relationQuery([
                'benefits', 'city'=>function($query){$query->field('id,name');}, 'district'=>function($query){$query->field('id,name');},
                'work_experience', 'education_level', 'job_info'=>function($query){$query->field('id,failed_reason');},
            ]);
            $this->success('', url('xilujob.job_manage/index'), ['job' => $job]);

        }
        $job = Job::with(['job_info','locations'=>['province','city','district']])->find($job->id);
        $job->benefit_ids = JobBenefit::where('job_id', $job->id)->column('benefit_id');
        $benefits = Benefit::getBenefits();
        $customBenefits = Benefit::alias('b')->join('xilujob_job_benefit_relation r','b.id=r.benefit_id')
            ->where('job_id', $job->id)->where('b.company_id','>',0)->field('b.*')->select();
        $benefits = array_merge($benefits, $customBenefits);

        //$this->assign('districts', Area::getDistrictsWith($this->city->id,false));
        $this->assign('districts', []);
        $this->assign('benefits', $benefits);
        $this->assign('work_experience_options', WorkExperience::getAll());
        $this->assign('education_levels', EducationLevel::getAll());
        $this->assign('agreement', SinglePage::where('short_tag','job_agreement')->find());
        $this->assignconfig('areas', Area::getAreaTree());

        //公司地址
        $companyAddress = CompanyAddress::where('company_id',$this->company->id)->select();
        $this->assign('companyAddress',$companyAddress);

        $this->assign('title', '发布职位');
        return $this->fetch('',['job'=>$job]);
    }

    /**
     * 添加地址
     * @return string
     * @throws Exception
     */
    public function working_place(){
        $this->model  = new CompanyAddress();
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        $params['company_id'] = $this->company->id;
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $result = false;
        Db::startTrans();
        try {
            $result = $this->model->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    public function del($id) {
        $job = Job::get($id);
        if (!$job || $job->publisher_id != $this->company->id) {
            $this->error(__('no record'));
        }
        try {
            $ret = Job::delJob($job);
        }catch (Exception $e){
            $this->error($e->getMessage());
        }
        $this->success('', '',['job'=>$job]);
    }

    public function batch_del($ids) {
        $ids = $ids ? explode(',',$ids) : [];
        $jobs = Job::where('publisher_id', $this->company->id)->whereIn('id',$ids)->select();
        Db::startTrans();
        try{
            foreach($jobs as $job) {
                $ret = Job::delJob($job);
            }
        }catch (Exception $e){
            Db::rollback();
            $this->error($e->getMessage());
        }
        Db::commit();
        $this->success('');
    }

    public function detail($id) {
        $job = Job::with([
            'job_info','job_category',
            'user'=>function( $query){$query->withField('id,nickname,avatar');},
            'city'=>function( $query){$query->withField('id,name,shortname');},
            'district'=>function( $query){$query->withField('id,name,shortname');},
            'work_experience'=>function( $query){$query->withField('id,name');},
            'education_level'=>function( $query){$query->withField('id,name');},
            'benefits'=>function( $query){$query->withField('id,name');},
            'enterpriseinfo'=>function( $query){$query->withField('id,logo,city_id,district_id,intro,company_type_id,industry_category_id,company_scale_id,company_name,full_name,environment_images,lng,lat,address');}
        ])->find($id);
        if(!$job) {
            $this->error(__('no record'));
        }
        if($job->status!=Job::STATUS_ENABLED) {
            $this->error('职位未上架');
        }
        if(config('site.hide_contact')) {
            $job->job_info->contact_phone = substr($job->job_info->contact_phone,0,3).'********';
        }
        $images = $job->job_info->environment_images ? : $job->enterpriseinfo->environment_images;
        $images = $images ? explode(',', $images) : [];
        //JobViewLog::viewJob($this->auth->id, $id);
        //$isFav = UserCollection::isFav($this->auth->id, $id, UserCollection::TYPE_JOB);
        $isApplying = JobApply::isApplying($this->auth->id, $id);
        //$isSignup = JobSignup::isSignup($this->auth->id, $id);

        if($this->auth->id) {
            $canComment = \app\common\model\xilujob\InterviewComment::where('job_id', $id)
                    ->where('user_id', $this->auth->id)
                    ->count() == 0;
        }else {
            $canComment = true;
        }
//        $commentList = \app\common\model\InterviewComment::where('job_id',$id)
//            ->with([
//                'job'=>function($query){$query->withField('id,job_name,status');},
//                'user'=>function($query){$query->withField('id,avatar,nickname');},
////                'enterpriseinfo'=>function($query){$query->withField('id,full_name,company_name');},
//            ])
//            ->order('id','desc')
//            ->paginate();
//        foreach($commentList as $comment) {
//            $comment->tags = $comment->tags ? explode(',', $comment->tags) : [];
//        }


        $relatedJobs = Job::getSimilarJobs($id);
        $this->assign('title', '职位详情');
        $this->assign('images', $images);
        $this->assign('can_comment', $canComment);
        $this->assign('related_jobs', $relatedJobs);
        $this->assign('inform_types', InformType::getAll());
//        $this->assign('job_comments', $commentList);
        return $this->fetch('',['job'=>$job,/*'is_fav'=>$isFav,*/ 'is_applying'=>$isApplying,
            /*'user'=>$user?['nickname'=>$user->nickname,'mobile'=>$user->mobile]:null,'is_signup'=>$isSignup*/]);
    }

    /**上架
     * @param $id
     * @throws \think\exception\DbException
     */
    public function switch_on($id) {
        $job = Job::get($id);
        if (!$job || $job->publisher_id != $this->company->id) {
            $this->error(__('no record'));
        }
        try {
            $ret = Job::switchOnJob($job);
        }catch (Exception $e){
            $this->error($e->getMessage());
        }

        $this->success('','',$ret);
    }

    public function batch_on($ids) {
        $ids = $ids ? explode(',',$ids) : [];
        $jobs = Job::where('publisher_id', $this->company->id)->whereIn('id',$ids)->select();
        Db::startTrans();
        $count = 0;
        try {
            foreach($jobs as $job) {
                $ret = Job::switchOnJob($job);
                $count += 1;
            }
        }catch (Exception $e){
            $this->error($e->getMessage());
        }

        Db::commit();
        if($count>0) {
            $this->success("成功发布{$count}个职位");
        }
        $this->error('上架失败');
    }

    public function switch_off($id) {
        $job = Job::get($id);
        if (!$job || $job->publisher_id != $this->company->id) {
            $this->error(__('no record'));
        }
        try {
            $ret = Job::switchOffJob($job);
        }catch (Exception $e){
            $this->error($e->getMessage());
        }
        $this->success('','',$ret);

    }

    public function batch_off($ids) {
        $ids = $ids ? explode(',',$ids) : [];
        $jobs = Job::where('publisher_id', $this->company->id)->whereIn('id',$ids)->select();
        Db::startTrans();
        $count = 0;
        try {
            foreach($jobs as $job) {
                $ret = Job::switchOffJob($job);
                $count += 1;
            }
        }catch (Exception $e){

        }
        Db::commit();
        if($count>0) {
            $this->success("成功暂停{$count}个职位");
        }
        $this->error('暂停失败');
    }


    //刷新职位
    public function refresh_job($id) {
        $job = Job::get($id);
        if (!$job || $job->publisher_id != $this->company->id) {
            $this->error(__('no record'));
        }
        $job_refresh_num = EnterpriseInfo::getAvailableNum($this->company->id,'refresh_num');
        if($job_refresh_num <= 0) {
            $this->error("您购买的职位刷新数已用尽，请前往购买");
        }
        //更新企业刷新数
        Db::startTrans();
        try {
            CompanyStatistics::where('company_id', $this->company->id)->update(['job_refresh_count'=>Db::raw('job_refresh_count+1')]);
            $job->save(['refreshtime'=>time(), 'refresh_date'=>date('Y-m-d')]);
            //减少次数
            EnterpriseInfo::where('company_id',$this->company->id)->update(['job_refresh_num'=>Db::raw('job_refresh_num-1')]);
        }catch (Exception $e){
            Db::rollback();
            $this->error($e->getMessage());
        }
        Db::commit();
        $this->success();
    }

    public function batch_refresh($ids) {
        $ids = $ids ? explode(',',$ids) : [];
        $jobs = Job::where('publisher_id', $this->company->id)->whereIn('id',$ids)->select();
        Db::startTrans();
        try {
            foreach($jobs as $job) {
                //更新企业刷新数
                CompanyStatistics::where('company_id', $this->company->id)->update(['job_refresh_count'=>Db::raw('job_refresh_count+1')]);
                $job->save(['refreshtime'=>time(), 'refresh_date'=>date('Y-m-d')]);
            }
        }catch (Exception $e){

        }

        Db::commit();
        $this->success();
    }

    public function preview() {
        $data = json_decode(html_entity_decode($this->request->get('data')),true);
        if(!isset($data['job'])) {
            $this->error('参数错误');
        }
        $data = $data['job'];
        if(!array_get($data,'city_id')) {
            $data['city_id'] = $this->city->id;
        }
        $job = new Job($data);
        $locations = [];
        foreach($data['locations'] as $location) {
            $locations[] = new JobLocation($location);
        }
        $job->locations = $locations;
        $job->benefits = isset($data['benefit_ids']) ? Benefit::whereIn('id',$data['benefit_ids'])->select() : [];

        return $this->fetch('preview', ['job'=>$job,'data'=>$data]);
    }

    public function get_benefit() {
        $name = $this->request->post('name');
        if(!$name) {
            $this->error();
        }
        $benefit = Benefit::where('name', $name)->find();
        if(!$benefit) {
            $benefit = new Benefit();
            $ret = $benefit->save(['name'=>$name, 'company_id'=>$this->auth->id]);
            if($ret===false) {
                $this->error($benefit->getError());
            }
        }
        $this->success('', '', ['benefit'=>$benefit]);
    }

    //地址
    public function select_company_address() {
        $company_id = $this->company->id;
        $lists = \app\common\model\xilujob\CompanyAddress::with([
            'province'=>function($query){$query->field('id,name');},
            'city'=>function($query){$query->field('id,name');},
            'district'=>function($query){$query->field('id,name');},

        ])->where('company_id', $company_id)
            ->order('id','desc')
            ->select();
        $this->success('','',$lists);
    }

    /**
     * 读取省市区数据,联动列表
     */
    public function area()
    {
        $pid = $this->request->param('pid', 0);
        $list = Area::where('pid', $pid)->field('id as value,name')->select();
        $this->success('', null, $list);
    }

    /**
     * 删除
     */
    public function del_address(){
        $id = $this->request->post('id');
        $row = $id ? \app\common\model\xilujob\CompanyAddress::where('id',$id)
            ->find() : null;
        if(!$row){
            $this->error("地址不存在");
        }
        #关联的地址
        $job = \app\common\model\xilujob\Job::alias("job")
            ->join("xilujob_job_location job_location",'job_location.job_id=job.id')
            ->where('job_location.company_address_id',$row->id)
            ->count(1);
        if($job){
            $this->error("有关联职位，不可删除");
        }
        $row->delete();
        $this->success('删除成功');
    }

}